# -*- coding: utf-8 -*-
import random
from datetime import datetime
from zc_core.spiders.base import BaseSpider
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from zc_core.dao.item_data_dao import ItemDataDao
from zc_core.dao.sku_dao import SkuDao
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter

from powerchina.rules import *


class PriceSpider(BaseSpider):
    name = "price"
    # 详情页url
    price_url = "https://emall.powerchina.cn/eshop/front/goods/getProduct.do"

    def __init__(self, batchNo=None, *args, **kwargs):
        super(PriceSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)

    def start_requests(self):
        sku_list = ItemDataDao().get_batch_data_list(self.batch_no, query={'spuId': {'$exists': False}})
        self.logger.info('全量: %s' % (len(sku_list)))
        random.shuffle(sku_list)
        for sku in sku_list:
            sku_id = sku.get("_id")
            yield scrapy.FormRequest(
                method='POST',
                url=self.price_url.format(sku_id),
                formdata={
                    'goodsId': sku_id,
                    'specJson': '',
                },
                meta={
                    'reqType': 'price',
                    'batchNo': self.batch_no,
                    "skuId": sku_id,
                },
                callback=self.parse_price,
                errback=self.error_back,
            )

    def parse_price(self, response):
        meta = response.meta
        sku_id = meta.get("skuId")
        item = parse_price(response)
        if item:
            self.logger.info('商品: [%s]' % sku_id)
            yield item
        else:
            self.logger.error('下架: sku=%s' % sku_id)
